<?php
// 应用公共文件


function error_json($message = '',$data = [],$code = 400)
{
    $param = [
        'err_code'=>$code,
        'msg'=>$message,
        'data'=>$data
    ];
    return json($param);
}

function success_json($message = '',$data = [],$code = 200)
{
    $param = [
        'err_code'=>$code,
        'msg'=>$message,
        'data'=>$data
    ];
    return json($param);
}



function error($message = '',$data = [],$code = 400){
    return error_json($message,$data,$code);
}


function base64_safe_encode($data)
{
    $base64 = base64_encode($data);
    return str_replace(['+','/'],['-','_'],$base64);
}

function base64_safe_decode($data)
{
    $data = str_replace(['-','_'],['+','/'],$data);
    return base64_decode($data);
}

/**
 * @param mixed[] $data
 * @param string[] $fields
 */
function array_only($data,$fields){
    $return = [];
    foreach($fields as $field){
        if(isset($data[$field])){
            $return[$field] = $data;
        }
    }
    return $data;
}


/**
 * 从容器中获取闭包并调用
 */
function call($name,$param){
    return app($name)(...$param);
}

/**
 * 将闭包放到容器中
 */
function call_bind($name,$call){
    app()->instance($name,$call);
}




function getDiskSize()
{
    $size = @disk_total_space(root_path()) ?? 0;
    return byte_format($size);
}


function byte_format($size,$dec=2){
    $a = ["B","KB","MB","GB","TB","PB","EB","ZB","YB"];
    $pos = 0;    
    while($size >= 1024) {
        $size /=1024;
        $pos++;
    }
    return round($size,$dec)." ".$a[$pos];
}


/**
 * 将类名转成缓存id前缀
 * @param $class
 * @return string
 */
function covertCacheKey($class){
    return str_replace(['\\','//'],'.',$class)."::";
}